﻿using CoreShop.Library;
using CoreShop.Model;
using Microsoft.AspNetCore.SignalR.Client;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CoreShop.App
{
    public partial class frmSignalClientMessage : Form
    {
        HubConnection conn1 = SignaRlHelp.GetConnection("conn1");
        public frmSignalClientMessage()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (conn1.State.ToString() == "Connected")
                {
                    txt_id.Text = conn1.ConnectionId;
                }
                else
                {
                    if (conn1.State.ToString() == "Disconnected")
                    {
                        await conn1.StartAsync();
                    }
                    else
                    {
                        await conn1.DisposeAsync();
                        conn1 = SignaRlHelp.GetConnection("conn1");
                        await conn1.StartAsync();
                    }
                }

                txt_id.Text = conn1.ConnectionId;
                SignalRUser user = new SignalRUser();
                user.connectionId = conn1.ConnectionId;
                user.storeId = text_store.Text;
                ClientMessage message = new ClientMessage();
                message.type = "userInfo";
                message.content = JsonConvert.SerializeObject(user);
                //连接成功后通知服务端写入用户信息
                await conn1.InvokeAsync<string>("CallByClient", $"{JsonConvert.SerializeObject(message)}");
            }
            catch (Exception ex)
            {
                SetMessageLog("【连接失败】"+ex.Message);
            }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            var msg = txt_senMsg.Text;
            await conn1.InvokeAsync<string>("CallByClient", $"客户端{conn1.ConnectionId}：发送给服务端{msg}");
        }


        /// <summary>
        /// 发送给服务器无返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button3_Click(object sender, EventArgs e)
        {
            await conn1.InvokeAsync<string>("CallAllClients", $"我是客户端{conn1.ConnectionId}，我给全员发消息" + txt_senMsg.Text);
        }

        /// <summary>
        /// 发送给服务器有返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button4_Click(object sender, EventArgs e)
        {

            var ret = await conn1.InvokeAsync<string>("CallByClientWithReturnValue", $"{txt_senMsg.Text}");
            txt_receive.Text = ret;

        }

        private async void button5_Click(object sender, EventArgs e)
        {
            await conn1.SendAsync("CallOtherClients", $"大家好我是客户端{conn1.ConnectionId}");
        }

        private async void btn_sendTarget_Click(object sender, EventArgs e)
        {
            await conn1.SendAsync("SendToClient", txt_targetId.Text, txt_senMsg.Text);
        }

        private async void Form1_Load(object sender, EventArgs e)
        {          
        }

        private void SetMessageLog(string msg)
        {
            try
            {
                if (txtMessageBox.TextLength > 5000) txtMessageBox.Clear();
                string msgLog = DateTime.Now.ToString() + ":"+ msg + "\r\n";
                txtMessageBox.Text += msgLog;                
            }
            catch (Exception)
            {
            }
        }

        private void SetReceiveMessage(string json)
        {
            try
            {
                var frombody = JsonConvert.DeserializeObject<FromBodyModel>(json);
                var msgLog = "【"+ EnumHelper.GetDescByValue<GlobalEnumVars.MessageCode>(frombody.code)+"】"+ json;                
                var bl = SignalClientServices.ReceiveMessage(frombody);
                if (bl) msgLog += "【成功】";
                else msgLog += "【失败】";
                SetMessageLog(msgLog);
            }
            catch 
            {            
            }
        }


        private void SignalClientMessage_Load(object sender, EventArgs e)
        {
            //被服务器端调用
            conn1.On<string>("CallByServer", (string msg) =>
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    try
                    {
                        if (txt_receive.TextLength > 5000) txt_receive.Clear();
                        txt_receive.Text += ($"{msg}");
                        SetReceiveMessage(msg);                      
                    }
                    catch (Exception)
                    {
                    }
                }));
            });
        }

        private void txtCommand_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }

        private void txtCommand_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtCommand.Text == "cmd")
                {
                    pnlOpration.Visible = true;
                }
                else if (string.IsNullOrEmpty(txtCommand.Text))
                {
                    pnlOpration.Visible = false;
                }
                
            }
        }
    }
}
